package com.cn.why.springcloudskills.service.impl;

import com.cn.why.springcloudskills.aop.AopLock;
import com.cn.why.springcloudskills.entity.SuccessKilled;
import com.cn.why.springcloudskills.mapper.SeckillMapper;
import com.cn.why.springcloudskills.mapper.SuccessKillMapper;
import com.cn.why.springcloudskills.service.SkillsService;
import com.cn.why.springcloudskills.util.Result;
import com.cn.why.springcloudskills.util.SeckillStatEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;

/**
 * 秒杀实现类
 */
@Service
public class SkillsServiceImpl implements SkillsService {
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private SuccessKillMapper successMapper;
    /**
     * 基于Aop的实现
     * @param seckillId
     * @param userId
     * @return
     */
    @Override
    @AopLock
    @Transactional
    public Result startSeckilAopLock(long seckillId, long userId) {
        //使用Aop+锁的实现,查询number的数量
        Long number = Long.valueOf(seckillMapper.selectNumbers(seckillId));
        if(number>0){
            //修改数据
            seckillMapper.updateNumbers(seckillId);
            //秒杀成功的用户
            SuccessKilled success = new SuccessKilled();
            success.setSeckillId(seckillId);
            success.setUserId(userId);
            success.setState(Short.parseShort(number+""));
            success.setCreateTime(new Timestamp(new Date().getTime()));
            //保存
            successMapper.save(success);
        }else{
            //秒杀失败
            return Result.fail(SeckillStatEnum.MUCH);
        }
        return Result.ok(SeckillStatEnum.SUCCESS);
    }

    /**
     * 修改数据库信息，用于测试功能
     * @param seckillId
     */
    @Override
    public void deleteSeckill(long seckillId) {
        seckillMapper.rNumbers(seckillId);
        successMapper.deleteSuccess(seckillId);
    }

    /**
     * 获取秒杀成功的数量
     * @param seckillId
     * @return
     */
    @Override
    public long getCountSkills(long seckillId) {
        return successMapper.getCountSkills(seckillId);
    }
}
